$(function () {
    var Id = getQueryString("Id");
    var gridUrl = '../sparepartsafestock/list';
    // 处理来自审核端的内容
    if (Id) {
        gridUrl += '?id=' + Id
    }
    $("#jqGrid").Grid({
        url: gridUrl,
        colModel: [
            {label: '名称', name: 'name', index: 'NAME'},
            {label: '规格', name: 'spec', index: 'SPEC'},
            {label: 'ERP编码', name: 'erpCode', index: 'ERP_CODE', width: 80},
            {label: '备件编码', name: 'partCode', index: 'PART_CODE', width: 70},
            {label: '供应厂家', name: 'producor', index: 'PRODUCOR', width: 90},
            {label: '备件类型', name: 'installPositionName', index: 'INSTALL_POSITION_NAME', width: 70},
            {label: '安全库存', name: 'safeNum', index: 'SAFE_NUM', width: 50},
            {
                label: '状态', index: 'STATE', width: 80,
                formatter: function (value, col, row) {
                    var v = row.state;
                    return sysEnums.SPARE_SAFE_STOCK_STATUS[v];
                }
            },
            {
                label: '更换详情', name: '', width: 60,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick = 'vm.sparePartsKey(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;更换详情</button>";
                }
            },
            {
                label: '审核详情', name: 'devCode', index: 'DEV_CODE', width: 60, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.shviewOption(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;详情</button>";
                }
            },
            {name: 'state', hidden: true},
            {name: 'deptId', hidden: true},
            {name: 'sparePartId', hidden: true},
            {name: 'id', index: 'ID', key: true, hidden: true},
        ]
    });
    // 获取备件类型
    vm.loadSparePartInstallPosition();
});

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        sparePartSafeStock: {
            sparePartsDesc: '', // 展示备件用
            remark: '',
            safeNum: '',
            holdingNum: '',
            sparePartId: '',
            name: '',
            spec: '',
            producor: '',
            id: '',
        },
        ruleValidate: {
            sparePartId: [
                {required: true, message: '备件必选！', trigger: 'change'}
            ],
            safeNum: [
                {required: true, type: 'number', message: '安全库存数必填！', trigger: 'change'}
            ]
        },
        statusList: enumsToList('SPARE_SAFE_STOCK_STATUS'),
        q: {
            Id: '',// 备件ID
            partCode: '', // 备件编码
            producor: '', // 厂家名称
            spec: '', // 规格
            erpCode: '', // 备件ERP编码
            partName: '',// 备件名称
            installPosition:'',//备件类型
            state: '', // 审批状态
            createUserName: '' // 录入人
        },
        // 备件安装部位列表
        sparePartInstallPositionList: [],
        // 审核参数VO
        approveParam: {
            approveIdList: [],
            status: 1,
            remark: ''
        },
        auditTableColumns: [
            {
                title: 'No.',
                type: 'index',
                width: 60,
                align: 'center'
            },
            {
                title: '审批角色',
                key: 'roleName',
                width: 100,
                align: 'center'
            },
            {
                title: '审批人',
                key: 'name',
                width: 100,
                align: 'center'
            },
            {
                title: '审批状态',
                key: 'state',
                width: 90,
                align: 'center',
                render: (h, params) => {
                    return sysEnums.CHECK_FLAG[params.row.status];
                }
            },
            {
                title: '审批时间',
                key: 'approveDate',
                width: 140,
                align: 'center'
            },
            {
                title: '审批备注',
                key: 'remark',
                align: 'center'
            }
        ],
        auditTableData: [], // 审批table数据
        // 关键零部件查看
        keyTableColumns: [
            {
                title: '备件编码',
                key: 'roleName',
                width: 100,
                align: 'center'
            },
            {
                title: '备件名称',
                key: 'name',
                width: 100,
                align: 'center'
            },
            {
                title: '开始计数时间',
                key: 'approveDate',
                width: 140,
                align: 'center'
            },
            {
                title: '平均寿命',
                key: 'remark',
                align: 'center'
            },
            {
                title: '剩余寿命',
                key: 'remark',
                align: 'center'
            }
        ],
        keyTableData: [], // 审批table数据
    },
    computed: {
        sparePartsDesc() {
            return `${this.sparePartSafeStock.name} ${this.sparePartSafeStock.spec} ${this.sparePartSafeStock.producor}`
        }
    },
    methods: {
        // 备件类型列表
        loadSparePartInstallPosition: function () {
            // 获取备件单位
            Ajax.request({
                url: '../sparepart/listCategory',
                async: false,
                successCallback: function (r) {
                    vm.sparePartInstallPositionList = r.list;
                }
            });
        },
        // 关键备件sparePartsKey
        sparePartsKey: function (res) {
            let data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysProcess/approve',
                params: {bussinessId: data.id},
                type: 'POST',
                successCallback: function (res) {
                    vm.keyTableData = res.approveProcessList;
                    layer.open({
                        type: 1,
                        title: "更换的关键零部件",
                        closeBtn: 0,
                        area: ['700px', '480px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: $('#sparePartsKeyArea')
                    });
                }
            });
        },
        //审核详情
        shviewOption: function (res) {
            let data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysProcess/approve',
                params: {bussinessId: data.id},
                type: 'POST',
                successCallback: function (res) {
                    vm.auditTableData = res.approveProcessList;
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['700px', '480px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: $('#auditHistoryArea')
                    });
                }
            });
        },
        getSparePart: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件',
                content: '../spare/sparePartSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.sparePartSafeStock.sparePartId = res.id;
                        vm.sparePartSafeStock.name = res.name;
                        vm.sparePartSafeStock.spec = res.spec;
                        vm.sparePartSafeStock.producor = res.producor;
                        layer.close(index);
                    }
                }
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.sparePartSafeStock = {
                remark: '',
                sparePartsDesc: '',
                name: '',
                spec: '',
                producor: '',
                safeNum: 1,
                holdingNum: 1,
                sparePartId: '',
                id: ''
            };
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            let url = vm.sparePartSafeStock.id == (null || '') ? "../sparepartsafestock/save" : "../sparepartsafestock/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.sparePartSafeStock),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        commitCheck: function () {
            // 编制完毕后提交审核
            var planId = getSelectedRow("#jqGrid");
            if (!planId) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.state == '1' || data.state == '2') {
                alert('当前安全库存审核中或已通过，无需重复提交!');
                return;
            }
            Ajax.request({
                url: '../sparepartsafestock/commitApprove',
                params: {'safeStockId': data.id},
                type: 'POST',
                successCallback: function (res) {
                    alert('提交成功!');
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                }
            });
        },
        deptCheck: function () {
            var data = getSelectedRowData('#jqGrid');
            if (data.state != '1') {
                alert('只有处于[部门审核]的计划才可以执行该操作！');
                return;
            }
            var _this = this;
            // 构建审批参数
            _this.approveParam = {
                approveIdList: [data.id],
                status: '1',
                remark: ''
            }
            openWindow({
                title: '车间安全库存审核',
                area: ['550px', '350px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../sparepartsafestock/check',
                        params: JSON.stringify(_this.approveParam),
                        contentType: "application/json",
                        type: 'POST',
                        successCallback: function (res) {
                            alert('审核成功!');
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sparepartsafestock/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../sparepartsafestock/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.sparePartSafeStock = r.sparePartSafeStock;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'partCode': vm.q.partCode,
                    'producor': vm.q.producor,
                    'installPosition':vm.q.installPosition,
                    'spec': vm.q.spec,
                    'erpCode': vm.q.erpCode,
                    'name': vm.q.partName,
                    'state': vm.q.state
                },
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                partCode: '',
                producor: '',
                spec: '',
                installPosition:'',
                erpCode: '',
                partName: '',
                state: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        exportData: function () {
            window.open('../sparepartsafestock/export');
        },
        handleBeforeUploadExcel: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleImportExcelSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.err
                })
            }
        },
        handleExcelFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleImportExcelError: function (err, file) {
            alert('导入失败');
        }
    }
});
